using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Mbs.Elements
{
    [Serializable]
    [DebuggerDisplay("{Values}")]
    class ElementCommandRepository : Dictionary<string, IElementCommand>, IElementCommandRepository
    {
        private ElementService Owner;
        public ElementCommandRepository(ElementService owner)
        {
            Owner = owner;
        }

        IElementCommand IElementCommandRepository.this[string commandName]
        {
            get
            {
                IElementCommand cmd = null;
                if (TryGetValue(commandName, out cmd))
                    return cmd;
                cmd = new ElementCommand(commandName/*, Owner.ExtensionMapService*/);
                base.Add(commandName, cmd);
                return cmd;
            }
        }

        void IElementCommandRepository.Remove(string commandName)
        {
            if (ContainsKey(commandName))
            {
                var cmd = base[commandName];
                if (cmd != null)
                    cmd.Dispose();
                base.Remove(commandName);
            }
        }

        public void Dispose()
        {
            var items = Values.ToArray();
            //Array.ForEach(items, item =>
            //{
            //    if (item != null)
            //        item.Dispose();
            //});

            Array.Clear(items, 0, items.Length);
            Clear();
        }

    }
}
